<template>
  <div class="factory-content" v-loading="loading">
    <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="0">
      <el-row :gutter="20">
        <el-col :span="6" align="left">
          <div class="factory-top">
            <el-form-item prop="title">
              <el-input v-model="editForm.title" placeholder="请输入客群名称">
                <icon-svg name="iconFacEdit" slot="prefix"></icon-svg>
              </el-input>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="18" align="right">
          <div class="btns">
            <span class="data-auth">数据范围：{{ $store.state.user.detailInfo.compNm }}</span>
            <span class="data-auth">
              历史版本：
              <el-date-picker
                type="month"
                value-format="yyyyMM"
                v-model="editForm.dataDate"
                placeholder="选择时间"
                :picker-options="pickOptions"
              ></el-date-picker>
            </span>
            <el-button @click="clear">
              <icon-svg name="iconCancel"></icon-svg>
              取消
            </el-button>
            <el-button type="primary" @click="handlePreview">
              <icon-svg name="iconFacEye"></icon-svg>
              预览
            </el-button>
            <el-button type="primary" @click="submit">
              <icon-svg name="iconSave"></icon-svg>
              保存
            </el-button>
            <el-button type="primary" :class="{ disabled: !editForm.derivedTagId }" @click="download">
              <icon-svg name="iconExport"></icon-svg>
              导出结果
            </el-button>
          </div>
        </el-col>
      </el-row>
      <div class="factory-content-wrapper tag-scrollbar">
        <!-- 导入列表 -->
        <import-config ref="factoryLogic" :tagId="editForm.tagId"></import-config>
        <!-- 画像 -->
        <factory-cust ref="factoryCust" @callback="addMap" @readTmpl="readTmpl"></factory-cust>
      </div>
    </el-form>
    <factory-tag-drawer ref="factoryTagDrawer"></factory-tag-drawer>
  </div>
</template>

<script>
import factoryCust from '../factory-cust-item'
import importConfig from './import-config'
import factoryTagDrawer from '../factory-tag-drawer'
import factory from '../factory'
export default {
  components: {
    factoryCust,
    importConfig,
    factoryTagDrawer
  },
  data() {
    return {
      loading: false,
      editForm: {
        groupId: '',
        tagId: '',
        derivedTagId: '',
        dataDate: '',
        title: '',
        derivedTag: {
          logicalOperation: 'and',
          tagList: []
        }
      },
      previewTime: '',
      baseTags: [],
      grpFlter: [],
      editFormRules: {
        title: [{ required: false, message: '客群名称不能为空', trigger: 'blur' }]
      },
      pickOptions: {
        disabledDate(time) {
          return time.getTime() > new Date().getTime()
        }
      }
    }
  },
  methods: {
    getDetail(params) {
      this.loading = true
      this.editForm.tagId = params.tagId
      this.$ajax({
        url: this.$ajax.setUrl(`tagFactory/getDerivedTag/${params.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.init(data.data)
        } else {
          this.$message.error(data.data || data.msg)
          this.loading = false
        }
      })
    },
    updateGroup(groupId) {
      this.editForm.groupId = groupId
    },
    init(data) {
      this.baseTags = data.baseTags
      this.editForm.derivedTagId = data.derivedTag.derivedTagId
      this.editForm.title = data.derivedTag.derivedTagNm
      let dataJson = JSON.parse(data.derivedTag.derivedTag)
      this.grpFlter = []
      dataJson.request.grpFlter.forEach(item => {
        let filterTag = this.baseTags.find(tag => tag.assetCode === item.mainGrp.labId)
        let params = {
          grpId: item.grpId,
          mainGrp: {
            labId: item.mainGrp.labId,
            groupTyp: item.mainGrp.groupTyp,
            labGrps: item.mainGrp.labGrps,
            groupName: dataJson.extra[item.grpId][item.mainGrp.labId].groupName,
            graphType: dataJson.extra[item.grpId][item.mainGrp.labId].graphType,
            labTbl: filterTag.labTbl,
            labFldMap: filterTag.labFldMap,
            rangeInfo: dataJson.extra[item.grpId][item.mainGrp.labId].rangeInfo,
            tagNm: filterTag.assetNm,
            valueType: filterTag.valueType,
            enums: filterTag.enums,
            enumType: dataJson.extra[item.grpId][item.mainGrp.labId].enumType,
            enumVal: dataJson.extra[item.grpId][item.mainGrp.labId].enumVal
          }
        }
        if (item.subGrp && item.subGrp.labId) {
          let filterSubTag = data.baseTags.find(tag => tag.assetCode === item.subGrp.labId)
          params.subGrp = {
            labId: item.subGrp.labId,
            groupTyp: item.subGrp.groupTyp,
            labGrps: item.subGrp.labGrps,
            groupName: dataJson.extra[item.grpId][item.subGrp.labId].groupName,
            graphType: dataJson.extra[item.grpId][item.subGrp.labId].graphType,
            labTbl: filterSubTag.labTbl,
            labFldMap: filterSubTag.labFldMap,
            rangeInfo: dataJson.extra[item.grpId][item.subGrp.labId].rangeInfo,
            tagNm: filterSubTag.assetNm,
            valueType: filterSubTag.valueType,
            enums: filterSubTag.enums
          }
        } else {
          if ((filterTag.valueType == '6' || filterTag.valueType == '7') && item.numGrp) {
            params.numGrp = item.numGrp
          }
        }
        this.grpFlter.push(params)
      })
      this.$nextTick(() => {
        let tagReault = JSON.parse(data.deriveTagResult)
        this.$refs.factoryLogic.toggleShow()
        const sourceData = {
          custGroupId: dataJson.request.custGroupId,
          dbNm: dataJson.request.labGrps.labs[0].labTbl.split('.')[0],
          tableNm: dataJson.request.labGrps.labs[0].labTbl.split('.')[1],
          fieldNm: dataJson.request.labGrps.labs[0].labFldMap
        }
        this.$refs.factoryLogic.setData(sourceData)
        this.$refs.factoryCust.toggleShow()
        this.previewTime = tagReault.runDat
        this.$nextTick(() => {
          this.$refs.factoryCust.update(Object.assign({}, tagReault, { grpFlter: this.grpFlter, refreshTime: true }))
        })
        this.loading = false
      })
    },
    clear() {
      if (!this.$refs.factoryLogic.showLogic) {
        this.$refs.factoryLogic.toggleShow()
      } else {
        this.$confirm('确定清除内容？').then(() => {
          this.loading = true
          this.editForm.derivedTag.tagList = []
          this.grpFlter = []
          this.$nextTick(() => (this.loading = false))
        })
      }
    },
    getParams() {
      return factory.initParams(this.editForm, this.grpFlter)
    },
    submit() {
      // if (!this.editForm.derivedTag.tagList.length) {
      //   this.$message.error('配置内容不能为空')
      //   return
      // }
      this.editFormRules.title[0].required = true
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let derivedTag = this.getParams()
          let result = {
            grpTotal: this.$refs.factoryCust.grpTotal,
            profile: this.$refs.factoryCust.profile,
            runCnt: 1,
            runDat: this.$refs.factoryCust.previewTime
          }
          this.initLabs(derivedTag)
          let param = {
            derivedTagNm: this.editForm.title,
            derivedTag: JSON.stringify(derivedTag),
            deriveTagResult: JSON.stringify(result)
          }
          if (this.editForm.groupId) param.groupId = this.editForm.groupId
          if (this.editForm.derivedTagId) {
            param.derivedTagId = this.editForm.derivedTagId
          }
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('tagFactory/saveDerivedTag'),
            method: 'post',
            data: this.$ajax.setData(param)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.editForm.derivedTagId = data.data
              if (this.$refs.factoryCust) this.$refs.factoryCust.updateTime()
              this.previewTime = this.$utils.formatDateTime(new Date())
              this.$message.success(data.msg)
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    initLabs(derivedTag) {
      const sourceData = this.$refs.factoryLogic.sourceData
      derivedTag.request.custGroupId = sourceData.custGroupId
      derivedTag.request.labGrps = {
        labs: [
          {
            labTbl: `${sourceData.dbNm}.${sourceData.tableNm}`,
            oprator: '=',
            datTyp: 'boolean',
            logicTyp: 'and',
            labFldMap: sourceData.fieldNm,
            dtTyp: '',
            labId: sourceData.custGroupId,
            isDerLabel: 1,
            val: '1',
            valLft: '',
            valRit: '',
            valArray: []
          }
        ],
        level: 1,
        logicTyp: 'and'
      }
      derivedTag.cache[sourceData.custGroupId] = { tagNm: this.editForm.title }
    },
    handlePreview() {
      this.editFormRules.title[0].required = false
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (!this.grpFlter.length) {
            let derivedTag = this.getParams()
            this.initLabs(derivedTag)
            let param = {
              derivedTagNm: this.editForm.title,
              derivedTag: JSON.stringify(derivedTag)
            }
            this.loading = true
            this.$ajax({
              url: this.$ajax.setUrl('tagFactory/getDeriveTagResult'),
              method: 'post',
              data: this.$ajax.setData(param),
              timeout: 0
            }).then(({ data }) => {
              if (data && data.code === '0') {
                if (this.$refs.factoryLogic.showLogic) this.$refs.factoryLogic.showLogic = false
                if (!this.$refs.factoryCust.showCust) {
                  this.$refs.factoryCust.showCust = true
                  this.$refs.factoryCust.setTotalInfo(data.data)
                }
                this.$refs.factoryCust.grpTotal = data.data.grpTotal
                this.$refs.factoryCust.runDat = data.data.runDat
              } else {
                this.$message.error(data.data || data.msg)
              }
              this.loading = false
            })
          } else this.$refs.factoryCust.updateFlter(this.grpFlter)
        }
      })
    },
    updatelabs() {
      if (this.$refs.factoryLogic.showLogic) this.$refs.factoryLogic.showLogic = false
      if (!this.$refs.factoryCust.showCust) this.$refs.factoryCust.showCust = true
    },
    addItem(item) {
      let params = {
        tagId: item.assetId,
        tagNm: item.assetNm,
        valueType: item.valueType.toString(),
        valueTypeCode: item.valueTypeCode,
        tagCode: item.assetCode,
        isDerLabel: item.isDerLabel,
        enums: item.enums,
        operationType: item.valueType.toString() === '3' ? '=' : '',
        operationValue: '',
        labTbl: item.labTbl,
        labFldMap: item.labFldMap,
        dictDatabaseType: item.dbVal
      }
      if (this.$refs.factoryCust.showCust) {
        if (this.$refs.factoryCust.tmplId) this.$refs.factoryCust.addCust(params)
        else this.$message.info('请选择添加画像方式！')
      }
    },
    addMap(grpFlter) {
      this.grpFlter = grpFlter
    },
    download() {
      if (!this.editForm.derivedTagId) {
        this.$message.info('请先保存客群！')
        return
      }
      let derivedTag = this.getParams()
      derivedTag.request.grpFlter = []
      this.$refs.factoryTagDrawer.showDrawer({
        derivedTagId: this.editForm.derivedTagId,
        groupId: this.editForm.groupId,
        derivedTagNm: this.editForm.title,
        derivedTag: JSON.stringify(derivedTag)
      })
    },
    readTmpl(tmplJson) {
      this.grpFlter = this.grpFlter.concat(JSON.parse(tmplJson))
      this.handlePreview()
    }
  }
}
</script>

<style lang="scss">
.factory-content {
  .factory-content-wrapper {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
}
</style>
